import 'dart:async';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/login_entity.dart';
import 'package:flutter_ncsjqz_getx/model/user_remark_list_entity.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/rong_base_logic.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/time.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:video_player/video_player.dart';

enum ConversationStatus {
  Normal, //正常
  VoiceRecorder, //语音输入，页面中间回弹出录音的 gif
}

class ChatLogic extends RongBaseLogic {
  /// 当前输入工具栏的状态
  ConversationStatus? currentStatus;

  /// 视频录制秒数
  int secondsVideo = 10;

  /// 当前页
  int pageIndex = 1;

  /// 一次加载20条消息记录
  int pageSize = 20;

  /// 底部面板开关
  bool showBottom = false;

  /// 底部面板分类  0 语音 1表情 2更多
  int bottomType = -1;

  /// 输入框的焦点实例
  FocusNode focusNode = FocusNode();

  /// 表情包集合
  List emojiList = [];

  /// 当前键盘是否是激活状态
  bool isKeyboardActived = false;

  /// 消息列表控制器
  ScrollController scrollController = ScrollController();

  /// 输入框控制器
  TextEditingController textEditingController = TextEditingController();

  /// 是否免打扰
  bool disturb = false;

  /// 当前用户群类型  1群主  2群员
  int groupType=0;

  // 底部更多工具栏
  List<ChatBottomEntity> bottomUtilList = [
    ChatBottomEntity(name: "图片", pic: "img.png"),
    ChatBottomEntity(name: "拍摄", pic: "video.png"),
  ];

  /// 目标群聊或者单聊的id
  String privateUserId='';

  /// 消息分类 3=群聊  1=单聊
  int conversationType = 1;

  /// 是否开启离线储存
  bool disableNotification = true;

  /// 消息集合
  List<MessageEntity> msgList = [];

  /// 被艾特人的列表
  List<User> userIdList=[];

  StreamSubscription<EventFn>? streamSubscriptionMessage ;

  String? name;

  String? usePic;

  // 获取自己的用户信息
  LoginData? loginData = getUserUtil();

  /// 是否显示底部菜单
  void setShowBottom() {
    showBottom = !showBottom;
    update();
  }

  /// listview滑动到指定位置
  void setListMax() {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) async {
      Future.delayed(Duration(milliseconds: 200),(){
        if(scrollController.position!=null){
          double lastOffset = scrollController.position.maxScrollExtent;
          scrollController.jumpTo(lastOffset);
        }
      });
      update();
    });
  }

  /// 关闭监听
  void messageListEventClose() async{
    if(streamSubscriptionMessage!=null) await streamSubscriptionMessage!.cancel();
  }

  /// 监听消息
  void messageListEvent(){
    // 订阅 eventbus , 对融云消息进行监听
    streamSubscriptionMessage = Constant.eventBus.on<EventFn>().listen((event) async {
      if(event.name=="rong"){
        getMessageList();
      }
    });
  }

  /// 获取消息记录
  Future getMessageList()async{
    msgList = [];
    List historyList = await  getHistoryMessage(conversationType,privateUserId,-1,pageSize*pageIndex);
    if(historyList==null) historyList=[];
    if(historyList.length<pageSize*pageIndex){
      pageIndex--;
    }
    print('pageIndex:$pageIndex');
    for(Message message in historyList){
      // 发送者idUserRemarkListEntity
      String? senderUserId = message.senderUserId;
      // 消息内容
      String content = message.originContentMap==null?message.content!.conversationDigest():message.originContentMap!['message'];
      // 时间转换
      String timer =TimeUtil.convertDateTime(message.sentTime!);
      // 单聊头像
      if(conversationType == RCConversationType.Private){
        // 谁发送的
        bool isMy = senderUserId!=privateUserId;
        String myPic = '';
        if(Constant.userDetailData!.userPic !=null){
          myPic = Constant.userDetailData!.userPic;
        }else{
          myPic = loginData!.picUrl ?? '';
        }
        msgList.add(MessageEntity(isMy, content,timer,isMy ? myPic :usePic,message.content,message.sentTime,message,name,senderUserId, loginData!.userId,type: message.objectName));
      }
      // 群头像
      if(conversationType==RCConversationType.Group){
        UserRemarkListEntity chatImageRemarkEntity = await DioService<UserRemarkListEntity>().queryUserRemarkList ({'userIds':  [message.senderUserId]});
        if(chatImageRemarkEntity.code == 0){
          String content = message.originContentMap==null?message.content!.conversationDigest():message.originContentMap!['message'];
          // 时间转换
          String timer = TimeUtil.convertDateTime(message.sentTime!);
          // 是不是自己
          bool isMy = loginData!.ryUserId == message.senderUserId;
          String? remarkName = chatImageRemarkEntity.data![0].remarkName;
          // 自己头像
          String myPic = '';
          if(Constant.userDetailData!.userPic !=null){
            myPic = Constant.userDetailData!.userPic;
          }else{
            myPic = loginData!.picUrl ?? '';
          }
          msgList.add(MessageEntity(isMy,content,timer,isMy ? myPic : chatImageRemarkEntity.data![0].picUrl,message.content,message.sentTime,message,remarkName,chatImageRemarkEntity.data![0].ryUserId,chatImageRemarkEntity.data![0].userId));
        }
      }
    }
    // 倒叙
    // msgList = msgList.reversed.toList();
    // 设置消息已读
    if(msgList.length > 0) sendReadReceiptMessage(conversationType,privateUserId);
    update();
  }

  /// 发送图片信息
  Future senImgMsg(path) async{
    // gif消息
    if (path!.endsWith("gif")) {
      GifMessage gifMsg = GifMessage.obtain(path);
      gifMsg.destructDuration = 30;
      Message? msg = await RongIMClient.sendMessage(conversationType, privateUserId, gifMsg,disableNotification: false);
      RongIMClient.onMessageSend=(int? messageId, int? status, int? code)async{
        print('messageId:$messageId  -----status:${status} ------ code:${code}');
        Message? result =await RongIMClient.getMessage(messageId!);
        if(status!=10){
          String timer = TimeUtil.convertDateTime(DateTime.now().millisecondsSinceEpoch);
          msgList.insert(0,MessageEntity(true,result!.content!.conversationDigest(),timer,Constant.userDetailData!.userPic != null ?Constant.userDetailData!.userPic: getUserUtil().picUrl,result.content,result.sentTime,result,getUserUtil().nikeName,getUserUtil().ryUserId,getUserUtil().userId));
        }
        setListMax();
      };
    } else {
      // 正常图片消息
      ImageMessage imgMsg = ImageMessage.obtain(path);
      imgMsg.destructDuration = 30;
      Message? msg = await RongIMClient.sendMessage(conversationType, privateUserId, imgMsg,disableNotification: false);
      RongIMClient.onMessageSend=(int? messageId, int? status, int? code)async{
        print('messageId:$messageId  -----status:${status} ------ code:${code}');
        Message? result =await RongIMClient.getMessage(messageId!);
        if(status!=10){
          String timer = TimeUtil.convertDateTime(DateTime.now().millisecondsSinceEpoch);
          msgList.insert(0,MessageEntity(true,result!.content!.conversationDigest(),timer,Constant.userDetailData!.userPic != null ?Constant.userDetailData!.userPic: getUserUtil().picUrl,result.content,result.sentTime,result,getUserUtil().nikeName,getUserUtil().ryUserId,getUserUtil().userId));
        }
        setListMax();
      };
    }
  }

  /// 发送短视频
  Future senVideoMsg(path) async{
    int seconds = 0;
    print("onFinishEvent con $conversationType targetId $privateUserId");
    VideoPlayerController _controller = VideoPlayerController.file(File(path));
    await _controller.initialize().then((val){
      _controller.setLooping(true);
      seconds = _controller.value.duration.inSeconds;
      print("视频时长：$seconds");
    });
    if(seconds>10) return toast("视频过大，无法发送，请选择10秒短视频");
    await _controller.dispose();
    SightMessage sightMessage = SightMessage.obtain(path, seconds);
    if (sightMessage.duration != null && sightMessage.duration! > 0) {
      if (conversationType == RCConversationType.Private) {
        sightMessage.destructDuration = seconds;
        // sightMessage.destructDuration = isSecretChat ? RCDuration.MediaMessageBurnDuration + recodeTime : 0;
      }
      // Message message = Message();
      // message.conversationType = conversationType;
      // message.targetId = targetId;
      // message.objectName = SightMessage.objectName;
      // message.content = sightMessage;
      // RongIMClient.sendIntactMessageWithCallBack(message, "", "",
      //     (int messageId, int status, int code) {
      //   String result = "messageId:$messageId status:$status code:$code";
      // });
      Message? message = await RongIMClient.sendMessage(conversationType, privateUserId, sightMessage);
      RongIMClient.onMessageSend=(int? messageId, int? status, int? code)async{
        print('messageId:$messageId  -----status:${status} ------ code:${code}');
        if(status==RCSentStatus.Sent){
          if(status!=10){
            String timer = TimeUtil.convertDateTime(DateTime.now().millisecondsSinceEpoch);
            msgList.insert(0,MessageEntity(true,message!.content!.conversationDigest(),timer,Constant.userDetailData!.userPic != null ?Constant.userDetailData!.userPic: getUserUtil().picUrl,message.content,message.sentTime,message,getUserUtil().nikeName,getUserUtil().ryUserId,getUserUtil().userId));
          }
          setListMax();
        }else if(status==RCSentStatus.Failed){
          BotToast.showText(text: '消息发送失败');
        }
      };
    } else {
      print("sightMessage duration is 0");
    }
  }
}

/// 更多菜单的实体
class ChatBottomEntity {
  String? name;
  String? pic;

  ChatBottomEntity({this.name, this.pic});
}

/// 信息实体
class MessageEntity {
  bool? own;//我发的还是对面发的
  String? msg;//消息内容
  String? cover;//头像
  String? nickName;//昵称
  String? timer;//时间
  MessageContent? content;
  String? ryUserId;//ry用户id
  int? timerInt;//时间戳
  String? type;//显示的类型  根据类型判断是图片还是文字或者视频
  Message? message;
  dynamic userId;

  MessageEntity(this.own, this.msg,this.timer,this.cover,this.content,this.timerInt,this.message,this.nickName,this.ryUserId,this.userId,
      {this.type});
}

/// @用户实体
class User{
  String? userId;
  String? userName;
}